package cn.pb.sms.contorller;


import cn.pb.sms.bean.Sensor;
import cn.pb.sms.bean.vo.SensorVo;
import cn.pb.sms.service.SensorService;
import cn.pb.sms.utils.FastJsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 裴波
 * @date 2021/1/30 18:31
 */
@Controller
public class SensorController {

    @Autowired
    private SensorService sensorService;

    /**
     * 查询传感器信息
     *
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String thymeleafTest(Model model, HttpServletRequest request) {
        if(request.getSession(false)!=null){
            if ("admin".equals(request.getSession(false).getAttribute("admin"))){
                SensorVo sensorInfoVo = sensorService.querySensorInfo();
                model.addAttribute("sensorInfoVo", sensorInfoVo);
                return "index";
            }
        }
        return "redirect:/login";
    }
    @RequestMapping("/")
    public String home(){
        return "redirect:/index";
    }
    /**
     * 新增传感器信息
     */
    @RequestMapping("/add")
    @ResponseBody
    public String add(String jsonObj) {
        try {
            sensorService.insertSensorInfo(jsonObj);
            return "插入成功";
        }catch (Exception e){
            return "插入失败，请检查你输入的参数";
        }
    }
    /**
     * 删除传感器信息
     */
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String delid) {
        try {
            sensorService.deleteSensorInfo(delid);
            return "删除成功";
        }catch (Exception e){
            return "删除失败，此数据数据库中不存在";
        }
    }
    /**
     * 修改传感器信息
     */
    @RequestMapping("/getedit")
    @ResponseBody
    public String getedit(String editid) {
        String json = sensorService.getEditInfo(editid);
        return json;
    }
    /**
     * 提交修改传感器信息
     */
    @RequestMapping("/edit")
    @ResponseBody
    @Transactional
    public String edit(String jsonObj) {
        try {
            Sensor sensor = FastJsonUtils.convertObject(jsonObj,Sensor.class);
            sensorService.deleteSensorInfo(sensor.getId());
            sensorService.insertSensorInfo(jsonObj);
            return "修改成功";
        }catch (Exception e){
            return "修改失败，请检查你输入的参数";
        }
    }
}
